package dto

import (
	"context"
	"engine/cache"
	"engine/consts"
	"engine/model"
	"github.com/goccy/go-json"
	"lib/db"
	"lib/log"
)

func GetAliConfig() (ossConfig *model.AliConfig, err error) {
	ossConfigJson, err := GetSystemConfiguration("ali-config")
	if err != nil {
		log.Errorf("获取阿里云配置失败: %v", err)
		return nil, err
	}
	if errOss := json.Unmarshal(ossConfigJson.JSON, &ossConfig); errOss != nil {
		log.Errorf("解析阿里云配置失败: %v", errOss)
		return nil, errOss
	}
	return
}

func GetCdnPrefix() string {
	aliConfig, _ := GetAliConfig()
	if aliConfig != nil {
		return aliConfig.OssConfig.CdnPrefix
	}
	return ""
}

func GetSystemConfiguration(code string) (*model.JSONType, error) {
	ctx := context.Background()
	var result model.JSONType
	sysConfigurationCacheKey := cache.GetSysConfigurationsCacheName(code)
	err := db.GetRedisClient().Get(ctx, sysConfigurationCacheKey).Scan(&result)
	if err != nil {
		err = db.GetDb().Table("sys_configurations").
			Select("value").
			Where("code = ? and status = ?", code, consts.StatusActive).
			Scan(&result).Error
		if err != nil {
			log.Error(err.Error())
			return nil, err
		}
		err = cache.RedisContextSet(ctx, sysConfigurationCacheKey, &result, 0)
		if err != nil {
			log.Error(err.Error())
			return nil, err
		}
	}
	return &result, nil
}

func GetEmailSmtpConfig() (*model.EmailSmtpConfig, error) {
	conf, err := GetSystemConfiguration("email")
	if err != nil {
		log.Errorf("获取邮箱配置失败: %v", err)
		return nil, err
	}
	var emailSmtpConfig model.EmailSmtpConfig
	err = json.Unmarshal(conf.JSON, &emailSmtpConfig)
	if err != nil {
		log.Errorf("解析邮箱配置失败: %v", err)
		return nil, err
	}
	return &emailSmtpConfig, nil
}

func GetEmailToSendDailyConfig() (emailStr string, err error) {
	ossConfigJson, err := GetSystemConfiguration("assign-email-to-send-daily")
	if err != nil {
		log.Errorf("获取邮件配置失败: %v", err)
		return "", err
	}
	if errOss := json.Unmarshal(ossConfigJson.JSON, &emailStr); errOss != nil {
		log.Errorf("获取邮件配置失败: %v", errOss)
		return "", errOss
	}
	return
}
